﻿using System;
using System.Web;
using System.Text;
using System.Threading;

namespace WebApplication1
{
    /// <summary>
    /// AutoCompleteHandler 的摘要说明
    /// </summary>
    public class AutoCompleteHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string keyWord = string.Empty;
            if (!string.IsNullOrEmpty(context.Request["KeyWord"]))
            {
                keyWord = context.Request["KeyWord"].Trim();
                ProcessRequest(context, keyWord);
            }
        }

        private void ProcessRequest(HttpContext context, string keyWord)
        {
            try
            {
                context.Response.ClearContent();
                context.Response.ContentType = ("text/xml;charset=UTF-8"); // 这里必须要设置，否则客户端接收不到这里写好的xml文件
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache); //没有缓存
                string result = CreateXmlResult(keyWord);
                context.Response.Write(result);
                context.Response.Flush();
                context.Response.End();
            }
            catch (ThreadAbortException ex)//这个异常不用处理
            {
                string err = ex.Message;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                //Logger.WriteFileLog(ex, Config.logDir);
            }
        }

        /// <summary>
        /// 生成返回提示结果对应的xml文件(实际编程重点关注这里就可以了)
        /// </summary>
        /// <param name="keyWord">实际项目中，应该使用返回的结果集，如泛型集合等等</param>
        /// <returns></returns>
        private string CreateXmlResult(string keyWord)
        {
            StringBuilder sb = new StringBuilder(300);
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sb.Append("<Results>");
            for (int i = 0; i < 10; i++)
            {
                sb.AppendFormat("<KeyWord>{0}_{1}</KeyWord>", keyWord, i);
            }
            sb.Append("</Results>");
            return sb.ToString().Trim();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


    }
}